﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Text.RegularExpressions;
using System.Collections;
using System.Globalization;

namespace Utils 
{
/// <summary>
/// Summary description for InputValidator
/// </summary>
public class InputValidator
{
		

	static InputValidator()
	{

	} //eof constructor

		
    public static bool IsValidInput (ref string msg  , string s)
    {
   //The following key words are not allowed in any user input 
    Regex re = new Regex ( "SHUTDOWN |WAIT |DELETE |SELECT |HAVING |NOWAIT |RESET |UPDATE |FROM |(--)|UNION | OR | LIKE |xp_cmdshell |XP_" , RegexOptions.IgnoreCase);
    Match m = re.Match ( s);
    if (m.Success)
        {
        msg = "Sorry, your request failed. If the problem persists please report " +
        "to your technical support the following message : SQL RESERVED COMMANDS CANNOT BE USED AS INPUT !!!";
        return false; 
        }
    else
        {
        return true;
        }
} //eof public bool IsValidInput (ref string ) 


		public static bool IsValidCommand ( ref string msg, string s )
		{
			//The following key words are not allowed in any user input 
			Regex re = new Regex ( "ADDUSERS|ARP|ASSOC|ASSOCIAT|AT|ATTRIB|BOOTCFG|BROWSTAT|CACLS|CALL|CD|CHANGE|CHKDSK|CHKNTFS|CHOICE|CIPHER|CleanMgr|CLEARMEM|CLIP|CLS|CLUSTER|CMD|COLOR|COMP|COMPACT|COMPRESS|CON2PRT|CONVERT|COPY|CSCcmd|CSVDE|DATE|Dcomcnfg|DEFRAG|DEL|DELPROF|DELTREE|DevCon|DIRUSE|DISKCOMP|DISKCOPY|DNSSTAT|DOSKEY|DSADD|DSQUERY|DSMOD|ECHO|ENDLOCAL|ERASE|EXIT|EXPAND|EXTRACT|FC|FDISK|FIND|FINDSTR|FOR|FOR|FOR|FORFILES|FORMAT|FREEDISK|FSUTIL|FTP|FTYPE|GLOBAL|GOTO|HELP|HFNETCHK|IF|IFMEMBER|KILL|LABEL|LOCAL|LOGEVENT|LOGOFF|LOGTIME|MAPISEND|MEM|MD|MKLINK|MODE|MORE|MOUNTVOL|MOVE|MOVEUSER|MSG|MSIEXEC|MSINFO|MSTSC|MUNGE|MV|NET|NETDOM|NETSH|NETSVC|NBTSTAT|NETSTAT|NOW|NSLOOKUP|NTBACKUP|NTRIGHTS|PATH|PATHPING|PAUSE|PERMS|PERFMON|PING|POPD|PORTQRY|PRINT|PRNCNFG|PRNMNGR|PROMPT|PsExec|PsFile|PsGetSid|PsInfo|PsKill|PsList|PsLoggedOn|PsLogList|PsPasswd|PsService|PsShutdown|PsSuspend|PUSHD|QGREP|RASDIAL|RASPHONE|RECOVER|REG|REGEDIT|REGSVR32|REGINI|REM|REN|REPLACE|RD|RDISK|RMTSHARE|ROBOCOPY|ROUTE|RUNAS|RUNDLL32|SCHTASKS|SCLIST|ScriptIt|SET|SETLOCAL|SETX|SHARE|SHIFT|SHORTCUT|SHOWGRPS|SHOWMBRS|SHUTDOWN|SLEEP|SOON|SORT|START|SU|SUBINACL|SUBST|TIMEOUT|TITLE|TOUCH|TRACERT|TYPE|USRSTAT|VER|VERIFY|WINDIFF|WINMSD|WINMSDP|WMIC|XCACLS|XCOPY", RegexOptions.IgnoreCase );
			Match m = re.Match ( s );
			if ( m.Success )
			{
				msg = "Sorry, your request failed. If the problem persists please report " +
        "to your technical support the following message : DANGEROUS WINDOWS CMD COMMANDS ARE FORBIDDEN FOR EXECUTION !!!";
				return false;
			}
			else
			{
				return true;
			}
		} //eof public bool IsValidInput (ref string ) 


	public static bool isValidPhoneNumber ( ref string msg , string s )
		{
				
				//^[\+]?(\d){6,15}$ -- the regex for a phone number

				Regex re = new Regex ( @"^[\+]?(\d{6,15})$" , RegexOptions.IgnoreCase );
				Match m = re.Match ( s );

				if (m.Success)
				{
						return true ;
				}
				else
				{
						msg = "Invalid phone number , The phone number should be in the following format +12345678";
						return false;
				}

		
		} //eof public static bool isValidPhoneNumber ( ref string msg , ref string s ) 


    //public bool isValidTextBox( ref msg , toInclude , dataType , value , ref title)
		public static bool IsValidTextBox ( ref string msg , int formType , object _toInclude , object _validable , 
				object _dataType , ref object _value , ref string title , object _colName , object _isPrimaryKey , int rowNum)
		{

				bool toInclude = Convert.ToBoolean ( _toInclude ) ;
				bool validable = Convert.ToBoolean ( _validable ) ;
				string dataType = Convert.ToString ( _dataType );
				string colName = Convert.ToString ( _colName );
				string value = Convert.ToString ( _value );
				bool isPrimaryKey;
				if ( _isPrimaryKey == null ) 
						isPrimaryKey = false ;
				else 
						isPrimaryKey = Convert.ToBoolean ( _isPrimaryKey );

				//COMM the primary keys are always valid - they are not show , neither visible
				if (isPrimaryKey)
						return true;

				if (rowNum == 0)
						return true;

				//comm - the values with asterix should not be empty, those without asterix can be
				if ( (formType == 2 || formType == 3 || formType == 4) && value.Trim ().Equals ( String.Empty ))
				{
						if (validable == true)
						{
								msg = "Please , fill in a value for the " + title + " field! Note that the cursor has been placed automaticaly in the text field ";
								return false;
						}
						if (validable == false)
								return true;
				}


				if (( formType == 1 || formType == 5 ) && value.Trim ().Equals ( String.Empty ))
				{
						return true ;
				}

						if (dataType.Equals ( "decimal" ) || dataType.Equals ( "numeric"))
						{
								try
								{
										//comm - check against Display Culture but save against DataBase culture
										CultureInfo cultureToUseInDisplay = Utils.Str.Formatter.GetCultureInfoToUse();
										CultureInfo cultureToUseInDataBase = Utils.Str.Formatter.GetDataBaseCulture ();
										double doubleValue = System.Convert.ToDouble ( value , cultureToUseInDisplay );
										value = String.Format ( cultureToUseInDataBase , "{0:N3}" , doubleValue );
										_value = value;			//set the passed object value referentce 
										Utils.Debugger.WriteIf ( "isValidTextBox The following value is going to database " + value );
										return true;
								}
								catch (System.FormatException e)
								{
										Utils.Debugger.WriteIf ( "The following Exception occured : \n" + e.Message );
										msg = "Please , fill in correct a correct decimal number for the text field with title \"" + title + " \". Correct examples - 100 000.10 ; 23.1 ; 2333333.4. Please, note that the cursor has been placed automaticaly in the textfield. ";
										return false;
								} //eof catch                                            }
						} //eof if it is decimal
						else if (( dataType.Equals ( "smalldatetime" ) ||
										dataType.Equals ( "datetime" ) ))
						{
								try
								{
										Convert.ToDateTime ( value );
										return true;
								}
								catch (System.FormatException e)
								{
										string columnName = Convert.ToString ( colName );
										SortedList sl = new SortedList ();
										sl.Add ( "today" , "datediff(dd, " + columnName + " , getdate()) = 0 AND " );
										sl.Add ( "yesterday" , "datediff(dd, " + columnName + " , getdate()) = 1 AND " );
										sl.Add ( "week" , "datediff(dd, " + columnName + " , getdate()) < 7 AND " );
										sl.Add ( "month" , "datediff(dd, " + columnName + " , getdate()) < 30 AND " );

										//if there are today , yesterday etc. in the dates
										for (int i = 0; i < sl.Count; i++)
										{
												if (Convert.ToString ( value ).Equals ( Convert.ToString ( sl.GetKey ( i ) ) ))
												{
														return true;
												}
										} //eof for
										Regex re = new Regex ( @"^last (\d){1,9} days$" , RegexOptions.IgnoreCase );
										Match m = re.Match ( Convert.ToString ( value ) );

										if (m.Success)
										{ return true; }

										Utils.Debugger.WriteIf ( "The following Exception occured : \n" + e.Message );
										msg = "Please , fill in correct data format for text fields with title \"" + title + " \". Correct examples 01.01.2008 or 1-Jan-2008. Please, note that the cursor has been placed automaticaly there. ";
										return false;
								} //eof catch                
						} //eof if it is date 

						else
						{
								//debugOk Utils.Debugger.WriteIf ( "InputValidator --- All cases went trough for title " + title);
								string s = (string) value;
								if (InputValidator.IsValidInput ( ref msg , s ))
										return true;
								else
										return false;
					} //eof else -- the last case strings 
				
		} //eof method IsValidTextBox( ref string msg , object toInclude , object dataType , object value , ref string title)



} //eof class InputValidator

} //eof namespace Utils
